import { useState } from "react";
import { LoginOutlined } from "@ant-design/icons";
import { Button, Col, Form, Input, Layout, App } from "antd";
import Card from "antd/es/card";
import Row from "antd/es/grid/row";
import { getColorPrimary, getRes } from "../../utils/constants";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import Title from "antd/es/typography/Title";
import { ssData } from "../../index";

const md5 = require("md5");

const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 8 },
};

const { Content, Footer } = Layout;

type LoginState = {
    userName: string;
    password: string;
};

const Index = () => {
    const [logging, setLogging] = useState<boolean>(false);
    const [loginState, setLoginState] = useState<LoginState>({
        userName: "",
        password: "",
    });

    const { message } = App.useApp();

    const navigate = useNavigate();

    const setValue = (value: LoginState) => {
        setLoginState(value);
    };

    const onFinish = (allValues: any) => {
        const loginForm = {
            userName: allValues.userName,
            password: md5(allValues.password),
            https: window.location.protocol === "https:",
        };
        setLogging(true);
        axios
            .post("/api/admin/login", loginForm)
            .then(({ data }) => {
                if (data.error) {
                    message.error(data.message).then(() => {
                        //ignore
                    });
                } else {
                    const query = new URLSearchParams(window.location.search);
                    if (query.get("redirectFrom") !== null && query.get("redirectFrom") !== "") {
                        //need reload page, because basename error
                        window.location.href = decodeURIComponent(query.get("redirectFrom") + "");
                    } else {
                        if (ssData) {
                            ssData.key = data.data.key;
                        }
                        navigate("/index", { replace: true });
                    }
                }
            })
            .finally(() => {
                setLogging(false);
            });
    };

    return (
        <Layout style={{ height: "100vh" }}>
            <Content
                style={{ minWidth: "100%", display: "flex", alignItems: "center", paddingRight: 24, paddingLeft: 24 }}
            >
                <Card
                    cover={
                        <div style={{ textAlign: "center" }}>
                            <img
                                alt={"bg"}
                                src={``}
                                style={{
                                    objectFit: "cover",
                                    opacity: 0.6,
                                    filter: "alpha(opacity=60)",
                                    width: "100%",
                                    position: "relative",
                                    display: "flex",
                                    flexDirection: "column",
                                    alignItems: "center",
                                    textAlign: "center",
                                    backgroundSize: "cover",
                                    height: "120px",
                                }}
                            />
                            <Title level={3} style={{ color: "#fff", background: getColorPrimary(), margin: 0 }}>
                                {getRes()["userNameAndPassword"]}
                            </Title>
                        </div>
                    }
                    style={{
                        textAlign: "center",
                        width: "100%",
                        marginRight: "auto",
                        marginLeft: "auto",
                        maxWidth: "660px",
                    }}
                >
                    <Form
                        {...layout}
                        initialValues={getRes().defaultLoginInfo}
                        onFinish={(values) => onFinish(values)}
                        onValuesChange={(_k, v) => setValue(v)}
                    >
                        <Form.Item label={getRes().userName} name="userName" rules={[{ required: true }]}>
                            <Input value={loginState.userName} />
                        </Form.Item>

                        <Form.Item label={getRes().password} name="password" rules={[{ required: true }]}>
                            <Input.Password value={loginState.password} />
                        </Form.Item>

                        <Row style={{ alignItems: "center", display: "flex" }}>
                            <Col xxl={24} xs={24}>
                                <Button loading={logging} type="primary" htmlType="submit">
                                    <LoginOutlined /> {getRes().login}
                                </Button>
                            </Col>
                        </Row>
                    </Form>
                </Card>
            </Content>
            <Footer style={{ textAlign: "center" }}>
                {getRes().copyrightCurrentYear} {getRes().websiteTitle}. All Rights Reserved.
            </Footer>
        </Layout>
    );
};

export default Index;
